<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlcall - Perl calling conventions from C - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlcall">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlcall.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlcall">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlcall">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlcall">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlcall">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlcall">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlcall">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlcall">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlcall">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlcall">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlcall">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlcall">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlcall">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlcall">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlcall">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlcall">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlcall">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlcall">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlcall">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlcall">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlcall">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlcall">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlcall">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlcall">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlcall">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlcall">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlcall">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlcall">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlcall">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlcall">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlcall">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlcall">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlcall">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlcall">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlcall">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlcall">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlcall">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlcall">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlcall">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlcall">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlcall">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlcall">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlcall">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlcall">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlcall">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlcall">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlcall">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlcall">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlcall">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlcall">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlcall">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlcall">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlcall">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlcall">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlcall">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlcall">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlcall">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlcall">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlcall">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlcall">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlcall">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlcall">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlcall">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlcall">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlcall">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlcall">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlcall">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlcall">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlcall">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlcall">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlcall">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlcall">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlcall">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlcall">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlcall">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlcall">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlcall">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlcall">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlcall">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlcall">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlcall">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlcall.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlcall">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlcall">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlcall">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlcall">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlcall">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlcall">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlcall">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlcall">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlcall">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlcall">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlcall">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlcall">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlcall">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlcall">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlcall">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlcall">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlcall">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlcall">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlcall">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlcall">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlcall">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlcall">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlcall">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlcall">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlcall">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlcall">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlcall">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlcall">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlcall">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlcall">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlcall">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlcall">5.35.1</a>
          <a class="dropdown-item active" href="perlcall.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlcall.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlcall.html">perlcall</a>
          <div id="more">
            (<a href="perlcall.txt">source</a>,
            <a href="https://metacpan.org/pod/perlcall">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlcall.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#THE-CALL_-FUNCTIONS">THE CALL_ FUNCTIONS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#FLAG-VALUES">FLAG VALUES</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_VOID">G_VOID</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_SCALAR">G_SCALAR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_ARRAY">G_ARRAY</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_DISCARD">G_DISCARD</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_NOARGS">G_NOARGS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_EVAL">G_EVAL</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#G_KEEPERR">G_KEEPERR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Determining-the-Context">Determining the Context</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#EXAMPLES">EXAMPLES</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlcall.html#No-Parameters,-Nothing-Returned">No Parameters, Nothing Returned</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Passing-Parameters">Passing Parameters</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Returning-a-Scalar">Returning a Scalar</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Returning-a-List-of-Values">Returning a List of Values</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Returning-a-List-in-Scalar-Context">Returning a List in Scalar Context</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Returning-Data-from-Perl-via-the-Parameter-List">Returning Data from Perl via the Parameter List</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-G_EVAL">Using G_EVAL</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-G_KEEPERR">Using G_KEEPERR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-call_sv">Using call_sv</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-call_argv">Using call_argv</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-call_method">Using call_method</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-GIMME_V">Using GIMME_V</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Using-Perl-to-Dispose-of-Temporaries">Using Perl to Dispose of Temporaries</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Strategies-for-Storing-Callback-Context-Information">Strategies for Storing Callback Context Information</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Alternate-Stack-Manipulation">Alternate Stack Manipulation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#Creating-and-Calling-an-Anonymous-Subroutine-in-C">Creating and Calling an Anonymous Subroutine in C</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#LIGHTWEIGHT-CALLBACKS">LIGHTWEIGHT CALLBACKS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#SEE-ALSO">SEE ALSO</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#AUTHOR">AUTHOR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlcall.html#DATE">DATE</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlcall.html#NAME">#</a>NAME</h1>

<p>perlcall - Perl calling conventions from C</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlcall.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>The purpose of this document is to show you how to call Perl subroutines directly from C, i.e., how to write <i>callbacks</i>.</p>

<p>Apart from discussing the C interface provided by Perl for writing callbacks the document uses a series of examples to show how the interface actually works in practice. In addition some techniques for coding callbacks are covered.</p>

<p>Examples where callbacks are necessary include</p>

<ul>

<li><p>An Error Handler</p>

<p>You have created an XSUB interface to an application&#39;s C API.</p>

<p>A fairly common feature in applications is to allow you to define a C function that will be called whenever something nasty occurs. What we would like is to be able to specify a Perl subroutine that will be called instead.</p>

</li>
<li><p>An Event-Driven Program</p>

<p>The classic example of where callbacks are used is when writing an event driven program, such as for an X11 application. In this case you register functions to be called whenever specific events occur, e.g., a mouse button is pressed, the cursor moves into a window or a menu item is selected.</p>

</li>
</ul>

<p>Although the techniques described here are applicable when embedding Perl in a C program, this is not the primary goal of this document. There are other details that must be considered and are specific to embedding Perl. For details on embedding Perl in C refer to <a href="perlembed.html">perlembed</a>.</p>

<p>Before you launch yourself head first into the rest of this document, it would be a good idea to have read the following two documents--<a href="perlxs.html">perlxs</a> and <a href="perlguts.html">perlguts</a>.</p>

<h1 id="THE-CALL_-FUNCTIONS"><a class="permalink" href="perlcall.html#THE-CALL_-FUNCTIONS">#</a><a id="THE"></a>THE CALL_ FUNCTIONS</h1>

<p>Although this stuff is easier to explain using examples, you first need be aware of a few important definitions.</p>

<p>Perl has a number of C functions that allow you to call Perl subroutines. They are</p>

<pre><code>I32 call_sv(SV* sv, I32 flags);
I32 call_pv(char *subname, I32 flags);
I32 call_method(char *methname, I32 flags);
I32 call_argv(char *subname, I32 flags, char **argv);</code></pre>

<p>The key function is <i>call_sv</i>. All the other functions are fairly simple wrappers which make it easier to call Perl subroutines in special cases. At the end of the day they will all call <i>call_sv</i> to invoke the Perl subroutine.</p>

<p>All the <i>call_*</i> functions have a <code>flags</code> parameter which is used to pass a bit mask of options to Perl. This bit mask operates identically for each of the functions. The settings available in the bit mask are discussed in <a href="perlcall.html#FLAG-VALUES">&quot;FLAG VALUES&quot;</a>.</p>

<p>Each of the functions will now be discussed in turn.</p>

<dl>

<dt id="call_sv"><a class="permalink" href="perlcall.html#call_sv">#</a>call_sv</dt>
<dd>

<p><i>call_sv</i> takes two parameters. The first, <code>sv</code>, is an SV*. This allows you to specify the Perl subroutine to be called either as a C string (which has first been converted to an SV) or a reference to a subroutine. The section, <a href="perlcall.html#Using-call_sv">&quot;Using call_sv&quot;</a>, shows how you can make use of <i>call_sv</i>.</p>

</dd>
<dt id="call_pv"><a class="permalink" href="perlcall.html#call_pv">#</a>call_pv</dt>
<dd>

<p>The function, <i>call_pv</i>, is similar to <i>call_sv</i> except it expects its first parameter to be a C char* which identifies the Perl subroutine you want to call, e.g., <code>call_pv(&quot;fred&quot;, 0)</code>. If the subroutine you want to call is in another package, just include the package name in the string, e.g., <code>&quot;pkg::fred&quot;</code>.</p>

</dd>
<dt id="call_method"><a class="permalink" href="perlcall.html#call_method">#</a>call_method</dt>
<dd>

<p>The function <i>call_method</i> is used to call a method from a Perl class. The parameter <code>methname</code> corresponds to the name of the method to be called. Note that the class that the method belongs to is passed on the Perl stack rather than in the parameter list. This class can be either the name of the class (for a static method) or a reference to an object (for a virtual method). See <a href="perlobj.html">perlobj</a> for more information on static and virtual methods and <a href="perlcall.html#Using-call_method">&quot;Using call_method&quot;</a> for an example of using <i>call_method</i>.</p>

</dd>
<dt id="call_argv"><a class="permalink" href="perlcall.html#call_argv">#</a>call_argv</dt>
<dd>

<p><i>call_argv</i> calls the Perl subroutine specified by the C string stored in the <code>subname</code> parameter. It also takes the usual <code>flags</code> parameter. The final parameter, <code>argv</code>, consists of a NULL-terminated list of C strings to be passed as parameters to the Perl subroutine. See <a href="perlcall.html#Using-call_argv">&quot;Using call_argv&quot;</a>.</p>

</dd>
</dl>

<p>All the functions return an integer. This is a count of the number of items returned by the Perl subroutine. The actual items returned by the subroutine are stored on the Perl stack.</p>

<p>As a general rule you should <i>always</i> check the return value from these functions. Even if you are expecting only a particular number of values to be returned from the Perl subroutine, there is nothing to stop someone from doing something unexpected--don&#39;t say you haven&#39;t been warned.</p>

<h1 id="FLAG-VALUES"><a class="permalink" href="perlcall.html#FLAG-VALUES">#</a><a id="FLAG"></a>FLAG VALUES</h1>

<p>The <code>flags</code> parameter in all the <i>call_*</i> functions is one of <code>G_VOID</code>, <code>G_SCALAR</code>, or <code>G_ARRAY</code>, which indicate the call context, OR&#39;ed together with a bit mask of any combination of the other G_* symbols defined below.</p>

<h2 id="G_VOID"><a class="permalink" href="perlcall.html#G_VOID">#</a>G_VOID</h2>

<p>Calls the Perl subroutine in a void context.</p>

<p>This flag has 2 effects:</p>

<ol>

<li><p>It indicates to the subroutine being called that it is executing in a void context (if it executes <i>wantarray</i> the result will be the undefined value).</p>

</li>
<li><p>It ensures that nothing is actually returned from the subroutine.</p>

</li>
</ol>

<p>The value returned by the <i>call_*</i> function indicates how many items have been returned by the Perl subroutine--in this case it will be 0.</p>

<h2 id="G_SCALAR"><a class="permalink" href="perlcall.html#G_SCALAR">#</a>G_SCALAR</h2>

<p>Calls the Perl subroutine in a scalar context. This is the default context flag setting for all the <i>call_*</i> functions.</p>

<p>This flag has 2 effects:</p>

<ol>

<li><p>It indicates to the subroutine being called that it is executing in a scalar context (if it executes <i>wantarray</i> the result will be false).</p>

</li>
<li><p>It ensures that only a scalar is actually returned from the subroutine. The subroutine can, of course, ignore the <i>wantarray</i> and return a list anyway. If so, then only the last element of the list will be returned.</p>

</li>
</ol>

<p>The value returned by the <i>call_*</i> function indicates how many items have been returned by the Perl subroutine - in this case it will be either 0 or 1.</p>

<p>If 0, then you have specified the G_DISCARD flag.</p>

<p>If 1, then the item actually returned by the Perl subroutine will be stored on the Perl stack - the section <a href="perlcall.html#Returning-a-Scalar">&quot;Returning a Scalar&quot;</a> shows how to access this value on the stack. Remember that regardless of how many items the Perl subroutine returns, only the last one will be accessible from the stack - think of the case where only one value is returned as being a list with only one element. Any other items that were returned will not exist by the time control returns from the <i>call_*</i> function. The section <a href="perlcall.html#Returning-a-List-in-Scalar-Context">&quot;Returning a List in Scalar Context&quot;</a> shows an example of this behavior.</p>

<h2 id="G_ARRAY"><a class="permalink" href="perlcall.html#G_ARRAY">#</a>G_ARRAY</h2>

<p>Calls the Perl subroutine in a list context.</p>

<p>As with G_SCALAR, this flag has 2 effects:</p>

<ol>

<li><p>It indicates to the subroutine being called that it is executing in a list context (if it executes <i>wantarray</i> the result will be true).</p>

</li>
<li><p>It ensures that all items returned from the subroutine will be accessible when control returns from the <i>call_*</i> function.</p>

</li>
</ol>

<p>The value returned by the <i>call_*</i> function indicates how many items have been returned by the Perl subroutine.</p>

<p>If 0, then you have specified the G_DISCARD flag.</p>

<p>If not 0, then it will be a count of the number of items returned by the subroutine. These items will be stored on the Perl stack. The section <a href="perlcall.html#Returning-a-List-of-Values">&quot;Returning a List of Values&quot;</a> gives an example of using the G_ARRAY flag and the mechanics of accessing the returned items from the Perl stack.</p>

<h2 id="G_DISCARD"><a class="permalink" href="perlcall.html#G_DISCARD">#</a>G_DISCARD</h2>

<p>By default, the <i>call_*</i> functions place the items returned from by the Perl subroutine on the stack. If you are not interested in these items, then setting this flag will make Perl get rid of them automatically for you. Note that it is still possible to indicate a context to the Perl subroutine by using either G_SCALAR or G_ARRAY.</p>

<p>If you do not set this flag then it is <i>very</i> important that you make sure that any temporaries (i.e., parameters passed to the Perl subroutine and values returned from the subroutine) are disposed of yourself. The section <a href="perlcall.html#Returning-a-Scalar">&quot;Returning a Scalar&quot;</a> gives details of how to dispose of these temporaries explicitly and the section <a href="perlcall.html#Using-Perl-to-Dispose-of-Temporaries">&quot;Using Perl to Dispose of Temporaries&quot;</a> discusses the specific circumstances where you can ignore the problem and let Perl deal with it for you.</p>

<h2 id="G_NOARGS"><a class="permalink" href="perlcall.html#G_NOARGS">#</a>G_NOARGS</h2>

<p>Whenever a Perl subroutine is called using one of the <i>call_*</i> functions, it is assumed by default that parameters are to be passed to the subroutine. If you are not passing any parameters to the Perl subroutine, you can save a bit of time by setting this flag. It has the effect of not creating the <code>@_</code> array for the Perl subroutine.</p>

<p>Although the functionality provided by this flag may seem straightforward, it should be used only if there is a good reason to do so. The reason for being cautious is that, even if you have specified the G_NOARGS flag, it is still possible for the Perl subroutine that has been called to think that you have passed it parameters.</p>

<p>In fact, what can happen is that the Perl subroutine you have called can access the <code>@_</code> array from a previous Perl subroutine. This will occur when the code that is executing the <i>call_*</i> function has itself been called from another Perl subroutine. The code below illustrates this</p>

<pre><code>sub fred
  { print &quot;@_\n&quot;  }

sub joe
  { &amp;fred }

&amp;joe(1,2,3);</code></pre>

<p>This will print</p>

<pre><code class="plaintext">1 2 3</code></pre>

<p>What has happened is that <code>fred</code> accesses the <code>@_</code> array which belongs to <code>joe</code>.</p>

<h2 id="G_EVAL"><a class="permalink" href="perlcall.html#G_EVAL">#</a>G_EVAL</h2>

<p>It is possible for the Perl subroutine you are calling to terminate abnormally, e.g., by calling <i>die</i> explicitly or by not actually existing. By default, when either of these events occurs, the process will terminate immediately. If you want to trap this type of event, specify the G_EVAL flag. It will put an <i>eval { }</i> around the subroutine call.</p>

<p>Whenever control returns from the <i>call_*</i> function you need to check the <code>$@</code> variable as you would in a normal Perl script.</p>

<p>The value returned from the <i>call_*</i> function is dependent on what other flags have been specified and whether an error has occurred. Here are all the different cases that can occur:</p>

<ul>

<li><p>If the <i>call_*</i> function returns normally, then the value returned is as specified in the previous sections.</p>

</li>
<li><p>If G_DISCARD is specified, the return value will always be 0.</p>

</li>
<li><p>If G_ARRAY is specified <i>and</i> an error has occurred, the return value will always be 0.</p>

</li>
<li><p>If G_SCALAR is specified <i>and</i> an error has occurred, the return value will be 1 and the value on the top of the stack will be <i>undef</i>. This means that if you have already detected the error by checking <code>$@</code> and you want the program to continue, you must remember to pop the <i>undef</i> from the stack.</p>

</li>
</ul>

<p>See <a href="perlcall.html#Using-G_EVAL">&quot;Using G_EVAL&quot;</a> for details on using G_EVAL.</p>

<h2 id="G_KEEPERR"><a class="permalink" href="perlcall.html#G_KEEPERR">#</a>G_KEEPERR</h2>

<p>Using the G_EVAL flag described above will always set <code>$@</code>: clearing it if there was no error, and setting it to describe the error if there was an error in the called code. This is what you want if your intention is to handle possible errors, but sometimes you just want to trap errors and stop them interfering with the rest of the program.</p>

<p>This scenario will mostly be applicable to code that is meant to be called from within destructors, asynchronous callbacks, and signal handlers. In such situations, where the code being called has little relation to the surrounding dynamic context, the main program needs to be insulated from errors in the called code, even if they can&#39;t be handled intelligently. It may also be useful to do this with code for <code>__DIE__</code> or <code>__WARN__</code> hooks, and <code>tie</code> functions.</p>

<p>The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in <i>call_*</i> functions that are used to implement such code, or with <code>eval_sv</code>. This flag has no effect on the <code>call_*</code> functions when G_EVAL is not used.</p>

<p>When G_KEEPERR is used, any error in the called code will terminate the call as usual, and the error will not propagate beyond the call (as usual for G_EVAL), but it will not go into <code>$@</code>. Instead the error will be converted into a warning, prefixed with the string &quot;\t(in cleanup)&quot;. This can be disabled using <code>no warnings &#39;misc&#39;</code>. If there is no error, <code>$@</code> will not be cleared.</p>

<p>Note that the G_KEEPERR flag does not propagate into inner evals; these may still set <code>$@</code>.</p>

<p>The G_KEEPERR flag was introduced in Perl version 5.002.</p>

<p>See <a href="perlcall.html#Using-G_KEEPERR">&quot;Using G_KEEPERR&quot;</a> for an example of a situation that warrants the use of this flag.</p>

<h2 id="Determining-the-Context"><a class="permalink" href="perlcall.html#Determining-the-Context">#</a><a id="Determining"></a>Determining the Context</h2>

<p>As mentioned above, you can determine the context of the currently executing subroutine in Perl with <i>wantarray</i>. The equivalent test can be made in C by using the <code>GIMME_V</code> macro, which returns <code>G_ARRAY</code> if you have been called in a list context, <code>G_SCALAR</code> if in a scalar context, or <code>G_VOID</code> if in a void context (i.e., the return value will not be used). An older version of this macro is called <code>GIMME</code>; in a void context it returns <code>G_SCALAR</code> instead of <code>G_VOID</code>. An example of using the <code>GIMME_V</code> macro is shown in section <a href="perlcall.html#Using-GIMME_V">&quot;Using GIMME_V&quot;</a>.</p>

<h1 id="EXAMPLES"><a class="permalink" href="perlcall.html#EXAMPLES">#</a>EXAMPLES</h1>

<p>Enough of the definition talk! Let&#39;s have a few examples.</p>

<p>Perl provides many macros to assist in accessing the Perl stack. Wherever possible, these macros should always be used when interfacing to Perl internals. We hope this should make the code less vulnerable to any changes made to Perl in the future.</p>

<p>Another point worth noting is that in the first series of examples I have made use of only the <i>call_pv</i> function. This has been done to keep the code simpler and ease you into the topic. Wherever possible, if the choice is between using <i>call_pv</i> and <i>call_sv</i>, you should always try to use <i>call_sv</i>. See <a href="perlcall.html#Using-call_sv">&quot;Using call_sv&quot;</a> for details.</p>

<h2 id="No-Parameters,-Nothing-Returned"><a class="permalink" href="perlcall.html#No-Parameters,-Nothing-Returned">#</a><a id="No"></a><a id="No-Parameters-Nothing-Returned"></a>No Parameters, Nothing Returned</h2>

<p>This first trivial example will call a Perl subroutine, <i>PrintUID</i>, to print out the UID of the process.</p>

<pre><code>sub PrintUID
{
    print &quot;UID is $&lt;\n&quot;;
}</code></pre>

<p>and here is a C function to call it</p>

<pre><code>static void
call_PrintUID()
{
    dSP;

    PUSHMARK(SP);
    call_pv(&quot;PrintUID&quot;, G_DISCARD|G_NOARGS);
}</code></pre>

<p>Simple, eh?</p>

<p>A few points to note about this example:</p>

<ol>

<li><p>Ignore <code>dSP</code> and <code>PUSHMARK(SP)</code> for now. They will be discussed in the next example.</p>

</li>
<li><p>We aren&#39;t passing any parameters to <i>PrintUID</i> so G_NOARGS can be specified.</p>

</li>
<li><p>We aren&#39;t interested in anything returned from <i>PrintUID</i>, so G_DISCARD is specified. Even if <i>PrintUID</i> was changed to return some value(s), having specified G_DISCARD will mean that they will be wiped by the time control returns from <i>call_pv</i>.</p>

</li>
<li><p>As <i>call_pv</i> is being used, the Perl subroutine is specified as a C string. In this case the subroutine name has been &#39;hard-wired&#39; into the code.</p>

</li>
<li><p>Because we specified G_DISCARD, it is not necessary to check the value returned from <i>call_pv</i>. It will always be 0.</p>

</li>
</ol>

<h2 id="Passing-Parameters"><a class="permalink" href="perlcall.html#Passing-Parameters">#</a><a id="Passing"></a>Passing Parameters</h2>

<p>Now let&#39;s make a slightly more complex example. This time we want to call a Perl subroutine, <code>LeftString</code>, which will take 2 parameters--a string ($s) and an integer ($n). The subroutine will simply print the first $n characters of the string.</p>

<p>So the Perl subroutine would look like this:</p>

<pre><code>sub LeftString
{
    my($s, $n) = @_;
    print substr($s, 0, $n), &quot;\n&quot;;
}</code></pre>

<p>The C function required to call <i>LeftString</i> would look like this:</p>

<pre><code>    static void
    call_LeftString(a, b)
    char * a;
    int b;
    {
        dSP;

	ENTER;
        SAVETMPS;

        PUSHMARK(SP);
        EXTEND(SP, 2);
        PUSHs(sv_2mortal(newSVpv(a, 0)));
        PUSHs(sv_2mortal(newSViv(b)));
        PUTBACK;

        call_pv(&quot;LeftString&quot;, G_DISCARD);

        FREETMPS;
        LEAVE;
    }</code></pre>

<p>Here are a few notes on the C function <i>call_LeftString</i>.</p>

<ol>

<li><p>Parameters are passed to the Perl subroutine using the Perl stack. This is the purpose of the code beginning with the line <code>dSP</code> and ending with the line <code>PUTBACK</code>. The <code>dSP</code> declares a local copy of the stack pointer. This local copy should <b>always</b> be accessed as <code>SP</code>.</p>

</li>
<li><p>If you are going to put something onto the Perl stack, you need to know where to put it. This is the purpose of the macro <code>dSP</code>--it declares and initializes a <i>local</i> copy of the Perl stack pointer.</p>

<p>All the other macros which will be used in this example require you to have used this macro.</p>

<p>The exception to this rule is if you are calling a Perl subroutine directly from an XSUB function. In this case it is not necessary to use the <code>dSP</code> macro explicitly--it will be declared for you automatically.</p>

</li>
<li><p>Any parameters to be pushed onto the stack should be bracketed by the <code>PUSHMARK</code> and <code>PUTBACK</code> macros. The purpose of these two macros, in this context, is to count the number of parameters you are pushing automatically. Then whenever Perl is creating the <code>@_</code> array for the subroutine, it knows how big to make it.</p>

<p>The <code>PUSHMARK</code> macro tells Perl to make a mental note of the current stack pointer. Even if you aren&#39;t passing any parameters (like the example shown in the section <a href="perlcall.html#No-Parameters%2C-Nothing-Returned">&quot;No Parameters, Nothing Returned&quot;</a>) you must still call the <code>PUSHMARK</code> macro before you can call any of the <i>call_*</i> functions--Perl still needs to know that there are no parameters.</p>

<p>The <code>PUTBACK</code> macro sets the global copy of the stack pointer to be the same as our local copy. If we didn&#39;t do this, <i>call_pv</i> wouldn&#39;t know where the two parameters we pushed were--remember that up to now all the stack pointer manipulation we have done is with our local copy, <i>not</i> the global copy.</p>

</li>
<li><p>Next, we come to EXTEND and PUSHs. This is where the parameters actually get pushed onto the stack. In this case we are pushing a string and an integer.</p>

<p>Alternatively you can use the XPUSHs() macro, which combines a <code>EXTEND(SP, 1)</code> and <code>PUSHs()</code>. This is less efficient if you&#39;re pushing multiple values.</p>

<p>See <a href="perlguts.html#XSUBs-and-the-Argument-Stack">&quot;XSUBs and the Argument Stack&quot; in perlguts</a> for details on how the PUSH macros work.</p>

</li>
<li><p>Because we created temporary values (by means of sv_2mortal() calls) we will have to tidy up the Perl stack and dispose of mortal SVs.</p>

<p>This is the purpose of</p>

<pre><code>ENTER;
SAVETMPS;</code></pre>

<p>at the start of the function, and</p>

<pre><code>FREETMPS;
LEAVE;</code></pre>

<p>at the end. The <code>ENTER</code>/<code>SAVETMPS</code> pair creates a boundary for any temporaries we create. This means that the temporaries we get rid of will be limited to those which were created after these calls.</p>

<p>The <code>FREETMPS</code>/<code>LEAVE</code> pair will get rid of any values returned by the Perl subroutine (see next example), plus it will also dump the mortal SVs we have created. Having <code>ENTER</code>/<code>SAVETMPS</code> at the beginning of the code makes sure that no other mortals are destroyed.</p>

<p>Think of these macros as working a bit like <code>{</code> and <code>}</code> in Perl to limit the scope of local variables.</p>

<p>See the section <a href="perlcall.html#Using-Perl-to-Dispose-of-Temporaries">&quot;Using Perl to Dispose of Temporaries&quot;</a> for details of an alternative to using these macros.</p>

</li>
<li><p>Finally, <i>LeftString</i> can now be called via the <i>call_pv</i> function. The only flag specified this time is G_DISCARD. Because we are passing 2 parameters to the Perl subroutine this time, we have not specified G_NOARGS.</p>

</li>
</ol>

<h2 id="Returning-a-Scalar"><a class="permalink" href="perlcall.html#Returning-a-Scalar">#</a><a id="Returning"></a>Returning a Scalar</h2>

<p>Now for an example of dealing with the items returned from a Perl subroutine.</p>

<p>Here is a Perl subroutine, <i>Adder</i>, that takes 2 integer parameters and simply returns their sum.</p>

<pre><code>sub Adder
{
    my($a, $b) = @_;
    $a + $b;
}</code></pre>

<p>Because we are now concerned with the return value from <i>Adder</i>, the C function required to call it is now a bit more complex.</p>

<pre><code>static void
call_Adder(a, b)
int a;
int b;
{
    dSP;
    int count;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(a)));
    PUSHs(sv_2mortal(newSViv(b)));
    PUTBACK;

    count = call_pv(&quot;Adder&quot;, G_SCALAR);

    SPAGAIN;

    if (count != 1)
        croak(&quot;Big trouble\n&quot;);

    printf (&quot;The sum of %d and %d is %d\n&quot;, a, b, POPi);

    PUTBACK;
    FREETMPS;
    LEAVE;
}</code></pre>

<p>Points to note this time are</p>

<ol>

<li><p>The only flag specified this time was G_SCALAR. That means that the <code>@_</code> array will be created and that the value returned by <i>Adder</i> will still exist after the call to <i>call_pv</i>.</p>

</li>
<li><p>The purpose of the macro <code>SPAGAIN</code> is to refresh the local copy of the stack pointer. This is necessary because it is possible that the memory allocated to the Perl stack has been reallocated during the <i>call_pv</i> call.</p>

<p>If you are making use of the Perl stack pointer in your code you must always refresh the local copy using SPAGAIN whenever you make use of the <i>call_*</i> functions or any other Perl internal function.</p>

</li>
<li><p>Although only a single value was expected to be returned from <i>Adder</i>, it is still good practice to check the return code from <i>call_pv</i> anyway.</p>

<p>Expecting a single value is not quite the same as knowing that there will be one. If someone modified <i>Adder</i> to return a list and we didn&#39;t check for that possibility and take appropriate action the Perl stack would end up in an inconsistent state. That is something you <i>really</i> don&#39;t want to happen ever.</p>

</li>
<li><p>The <code>POPi</code> macro is used here to pop the return value from the stack. In this case we wanted an integer, so <code>POPi</code> was used.</p>

<p>Here is the complete list of POP macros available, along with the types they return.</p>

<pre><code class="plaintext">POPs	SV
POPp	pointer (PV)
POPpbytex   pointer to bytes (PV)
POPn	double (NV)
POPi	integer (IV)
POPu        unsigned integer (UV)
POPl	long
POPul       unsigned long</code></pre>

<p>Since these macros have side-effects don&#39;t use them as arguments to macros that may evaluate their argument several times, for example:</p>

<pre><code>/* Bad idea, don&#39;t do this */
STRLEN len;
const char *s = SvPV(POPs, len);</code></pre>

<p>Instead, use a temporary:</p>

<pre><code>STRLEN len;
SV *sv = POPs;
const char *s = SvPV(sv, len);</code></pre>

<p>or a macro that guarantees it will evaluate its arguments only once:</p>

<pre><code>STRLEN len;
const char *s = SvPVx(POPs, len);</code></pre>

</li>
<li><p>The final <code>PUTBACK</code> is used to leave the Perl stack in a consistent state before exiting the function. This is necessary because when we popped the return value from the stack with <code>POPi</code> it updated only our local copy of the stack pointer. Remember, <code>PUTBACK</code> sets the global stack pointer to be the same as our local copy.</p>

</li>
</ol>

<h2 id="Returning-a-List-of-Values"><a class="permalink" href="perlcall.html#Returning-a-List-of-Values">#</a><a id="Returning1"></a>Returning a List of Values</h2>

<p>Now, let&#39;s extend the previous example to return both the sum of the parameters and the difference.</p>

<p>Here is the Perl subroutine</p>

<pre><code>sub AddSubtract
{
   my($a, $b) = @_;
   ($a+$b, $a-$b);
}</code></pre>

<p>and this is the C function</p>

<pre><code>static void
call_AddSubtract(a, b)
int a;
int b;
{
    dSP;
    int count;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(a)));
    PUSHs(sv_2mortal(newSViv(b)));
    PUTBACK;

    count = call_pv(&quot;AddSubtract&quot;, G_ARRAY);

    SPAGAIN;

    if (count != 2)
        croak(&quot;Big trouble\n&quot;);

    printf (&quot;%d - %d = %d\n&quot;, a, b, POPi);
    printf (&quot;%d + %d = %d\n&quot;, a, b, POPi);

    PUTBACK;
    FREETMPS;
    LEAVE;
}</code></pre>

<p>If <i>call_AddSubtract</i> is called like this</p>

<pre><code>call_AddSubtract(7, 4);</code></pre>

<p>then here is the output</p>

<pre><code class="plaintext">7 - 4 = 3
7 + 4 = 11</code></pre>

<p>Notes</p>

<ol>

<li><p>We wanted list context, so G_ARRAY was used.</p>

</li>
<li><p>Not surprisingly <code>POPi</code> is used twice this time because we were retrieving 2 values from the stack. The important thing to note is that when using the <code>POP*</code> macros they come off the stack in <i>reverse</i> order.</p>

</li>
</ol>

<h2 id="Returning-a-List-in-Scalar-Context"><a class="permalink" href="perlcall.html#Returning-a-List-in-Scalar-Context">#</a><a id="Returning2"></a>Returning a List in Scalar Context</h2>

<p>Say the Perl subroutine in the previous section was called in a scalar context, like this</p>

<pre><code>static void
call_AddSubScalar(a, b)
int a;
int b;
{
    dSP;
    int count;
    int i;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(a)));
    PUSHs(sv_2mortal(newSViv(b)));
    PUTBACK;

    count = call_pv(&quot;AddSubtract&quot;, G_SCALAR);

    SPAGAIN;

    printf (&quot;Items Returned = %d\n&quot;, count);

    for (i = 1; i &lt;= count; ++i)
        printf (&quot;Value %d = %d\n&quot;, i, POPi);

    PUTBACK;
    FREETMPS;
    LEAVE;
}</code></pre>

<p>The other modification made is that <i>call_AddSubScalar</i> will print the number of items returned from the Perl subroutine and their value (for simplicity it assumes that they are integer). So if <i>call_AddSubScalar</i> is called</p>

<pre><code>call_AddSubScalar(7, 4);</code></pre>

<p>then the output will be</p>

<pre><code class="plaintext">Items Returned = 1
Value 1 = 3</code></pre>

<p>In this case the main point to note is that only the last item in the list is returned from the subroutine. <i>AddSubtract</i> actually made it back to <i>call_AddSubScalar</i>.</p>

<h2 id="Returning-Data-from-Perl-via-the-Parameter-List"><a class="permalink" href="perlcall.html#Returning-Data-from-Perl-via-the-Parameter-List">#</a><a id="Returning3"></a>Returning Data from Perl via the Parameter List</h2>

<p>It is also possible to return values directly via the parameter list--whether it is actually desirable to do it is another matter entirely.</p>

<p>The Perl subroutine, <i>Inc</i>, below takes 2 parameters and increments each directly.</p>

<pre><code>sub Inc
{
    ++ $_[0];
    ++ $_[1];
}</code></pre>

<p>and here is a C function to call it.</p>

<pre><code>    static void
    call_Inc(a, b)
    int a;
    int b;
    {
        dSP;
        int count;
        SV * sva;
        SV * svb;

        ENTER;
        SAVETMPS;

        sva = sv_2mortal(newSViv(a));
        svb = sv_2mortal(newSViv(b));

        PUSHMARK(SP);
        EXTEND(SP, 2);
        PUSHs(sva);
        PUSHs(svb);
        PUTBACK;

        count = call_pv(&quot;Inc&quot;, G_DISCARD);

        if (count != 0)
            croak (&quot;call_Inc: expected 0 values from &#39;Inc&#39;, got %d\n&quot;,
                   count);

        printf (&quot;%d + 1 = %d\n&quot;, a, SvIV(sva));
        printf (&quot;%d + 1 = %d\n&quot;, b, SvIV(svb));

	FREETMPS;
	LEAVE;
    }</code></pre>

<p>To be able to access the two parameters that were pushed onto the stack after they return from <i>call_pv</i> it is necessary to make a note of their addresses--thus the two variables <code>sva</code> and <code>svb</code>.</p>

<p>The reason this is necessary is that the area of the Perl stack which held them will very likely have been overwritten by something else by the time control returns from <i>call_pv</i>.</p>

<h2 id="Using-G_EVAL"><a class="permalink" href="perlcall.html#Using-G_EVAL">#</a><a id="Using"></a>Using G_EVAL</h2>

<p>Now an example using G_EVAL. Below is a Perl subroutine which computes the difference of its 2 parameters. If this would result in a negative result, the subroutine calls <i>die</i>.</p>

<pre><code>sub Subtract
{
    my ($a, $b) = @_;

    die &quot;death can be fatal\n&quot; if $a &lt; $b;

    $a - $b;
}</code></pre>

<p>and some C to call it</p>

<pre><code>static void
call_Subtract(a, b)
int a;
int b;
{
    dSP;
    int count;
    SV *err_tmp;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(a)));
    PUSHs(sv_2mortal(newSViv(b)));
    PUTBACK;

    count = call_pv(&quot;Subtract&quot;, G_EVAL|G_SCALAR);

    SPAGAIN;

    /* Check the eval first */
    err_tmp = ERRSV;
    if (SvTRUE(err_tmp))
    {
        printf (&quot;Uh oh - %s\n&quot;, SvPV_nolen(err_tmp));
        POPs;
    }
    else
    {
      if (count != 1)
       croak(&quot;call_Subtract: wanted 1 value from &#39;Subtract&#39;, got %d\n&quot;,
             count);

        printf (&quot;%d - %d = %d\n&quot;, a, b, POPi);
    }

    PUTBACK;
    FREETMPS;
    LEAVE;
}</code></pre>

<p>If <i>call_Subtract</i> is called thus</p>

<pre><code class="plaintext">call_Subtract(4, 5)</code></pre>

<p>the following will be printed</p>

<pre><code class="plaintext">Uh oh - death can be fatal</code></pre>

<p>Notes</p>

<ol>

<li><p>We want to be able to catch the <i>die</i> so we have used the G_EVAL flag. Not specifying this flag would mean that the program would terminate immediately at the <i>die</i> statement in the subroutine <i>Subtract</i>.</p>

</li>
<li><p>The code</p>

<pre><code>err_tmp = ERRSV;
if (SvTRUE(err_tmp))
{
    printf (&quot;Uh oh - %s\n&quot;, SvPV_nolen(err_tmp));
    POPs;
}</code></pre>

<p>is the direct equivalent of this bit of Perl</p>

<pre><code>print &quot;Uh oh - $@\n&quot; if $@;</code></pre>

<p><code>PL_errgv</code> is a perl global of type <code>GV *</code> that points to the symbol table entry containing the error. <code>ERRSV</code> therefore refers to the C equivalent of <code>$@</code>. We use a local temporary, <code>err_tmp</code>, since <code>ERRSV</code> is a macro that calls a function, and <code>SvTRUE(ERRSV)</code> would end up calling that function multiple times.</p>

</li>
<li><p>Note that the stack is popped using <code>POPs</code> in the block where <code>SvTRUE(err_tmp)</code> is true. This is necessary because whenever a <i>call_*</i> function invoked with G_EVAL|G_SCALAR returns an error, the top of the stack holds the value <i>undef</i>. Because we want the program to continue after detecting this error, it is essential that the stack be tidied up by removing the <i>undef</i>.</p>

</li>
</ol>

<h2 id="Using-G_KEEPERR"><a class="permalink" href="perlcall.html#Using-G_KEEPERR">#</a><a id="Using1"></a>Using G_KEEPERR</h2>

<p>Consider this rather facetious example, where we have used an XS version of the call_Subtract example above inside a destructor:</p>

<pre><code>    package Foo;
    sub new { bless {}, $_[0] }
    sub Subtract {
        my($a,$b) = @_;
        die &quot;death can be fatal&quot; if $a &lt; $b;
        $a - $b;
    }
    sub DESTROY { call_Subtract(5, 4); }
    sub foo { die &quot;foo dies&quot;; }

    package main;
    {
	my $foo = Foo-&gt;new;
	eval { $foo-&gt;foo };
    }
    print &quot;Saw: $@&quot; if $@;             # should be, but isn&#39;t</code></pre>

<p>This example will fail to recognize that an error occurred inside the <code>eval {}</code>. Here&#39;s why: the call_Subtract code got executed while perl was cleaning up temporaries when exiting the outer braced block, and because call_Subtract is implemented with <i>call_pv</i> using the G_EVAL flag, it promptly reset <code>$@</code>. This results in the failure of the outermost test for <code>$@</code>, and thereby the failure of the error trap.</p>

<p>Appending the G_KEEPERR flag, so that the <i>call_pv</i> call in call_Subtract reads:</p>

<pre><code>count = call_pv(&quot;Subtract&quot;, G_EVAL|G_SCALAR|G_KEEPERR);</code></pre>

<p>will preserve the error and restore reliable error handling.</p>

<h2 id="Using-call_sv"><a class="permalink" href="perlcall.html#Using-call_sv">#</a><a id="Using2"></a>Using call_sv</h2>

<p>In all the previous examples I have &#39;hard-wired&#39; the name of the Perl subroutine to be called from C. Most of the time though, it is more convenient to be able to specify the name of the Perl subroutine from within the Perl script, and you&#39;ll want to use <a href="perlapi.html#call_sv">call_sv</a>.</p>

<p>Consider the Perl code below</p>

<pre><code>sub fred
{
    print &quot;Hello there\n&quot;;
}

CallSubPV(&quot;fred&quot;);</code></pre>

<p>Here is a snippet of XSUB which defines <i>CallSubPV</i>.</p>

<pre><code>    void
    CallSubPV(name)
    	char *	name
    	CODE:
	PUSHMARK(SP);
	call_pv(name, G_DISCARD|G_NOARGS);</code></pre>

<p>That is fine as far as it goes. The thing is, the Perl subroutine can be specified as only a string, however, Perl allows references to subroutines and anonymous subroutines. This is where <i>call_sv</i> is useful.</p>

<p>The code below for <i>CallSubSV</i> is identical to <i>CallSubPV</i> except that the <code>name</code> parameter is now defined as an SV* and we use <i>call_sv</i> instead of <i>call_pv</i>.</p>

<pre><code>    void
    CallSubSV(name)
    	SV *	name
    	CODE:
	PUSHMARK(SP);
	call_sv(name, G_DISCARD|G_NOARGS);</code></pre>

<p>Because we are using an SV to call <i>fred</i> the following can all be used:</p>

<pre><code>CallSubSV(&quot;fred&quot;);
CallSubSV(\&amp;fred);
$ref = \&amp;fred;
CallSubSV($ref);
CallSubSV( sub { print &quot;Hello there\n&quot; } );</code></pre>

<p>As you can see, <i>call_sv</i> gives you much greater flexibility in how you can specify the Perl subroutine.</p>

<p>You should note that, if it is necessary to store the SV (<code>name</code> in the example above) which corresponds to the Perl subroutine so that it can be used later in the program, it not enough just to store a copy of the pointer to the SV. Say the code above had been like this:</p>

<pre><code>    static SV * rememberSub;

    void
    SaveSub1(name)
    	SV *	name
    	CODE:
	rememberSub = name;

    void
    CallSavedSub1()
    	CODE:
	PUSHMARK(SP);
	call_sv(rememberSub, G_DISCARD|G_NOARGS);</code></pre>

<p>The reason this is wrong is that, by the time you come to use the pointer <code>rememberSub</code> in <code>CallSavedSub1</code>, it may or may not still refer to the Perl subroutine that was recorded in <code>SaveSub1</code>. This is particularly true for these cases:</p>

<pre><code>SaveSub1(\&amp;fred);
CallSavedSub1();

SaveSub1( sub { print &quot;Hello there\n&quot; } );
CallSavedSub1();</code></pre>

<p>By the time each of the <code>SaveSub1</code> statements above has been executed, the SV*s which corresponded to the parameters will no longer exist. Expect an error message from Perl of the form</p>

<pre><code class="plaintext">Can&#39;t use an undefined value as a subroutine reference at ...</code></pre>

<p>for each of the <code>CallSavedSub1</code> lines.</p>

<p>Similarly, with this code</p>

<pre><code>$ref = \&amp;fred;
SaveSub1($ref);
$ref = 47;
CallSavedSub1();</code></pre>

<p>you can expect one of these messages (which you actually get is dependent on the version of Perl you are using)</p>

<pre><code class="plaintext">Not a CODE reference at ...
Undefined subroutine &amp;main::47 called ...</code></pre>

<p>The variable $ref may have referred to the subroutine <code>fred</code> whenever the call to <code>SaveSub1</code> was made but by the time <code>CallSavedSub1</code> gets called it now holds the number <code>47</code>. Because we saved only a pointer to the original SV in <code>SaveSub1</code>, any changes to $ref will be tracked by the pointer <code>rememberSub</code>. This means that whenever <code>CallSavedSub1</code> gets called, it will attempt to execute the code which is referenced by the SV* <code>rememberSub</code>. In this case though, it now refers to the integer <code>47</code>, so expect Perl to complain loudly.</p>

<p>A similar but more subtle problem is illustrated with this code:</p>

<pre><code>$ref = \&amp;fred;
SaveSub1($ref);
$ref = \&amp;joe;
CallSavedSub1();</code></pre>

<p>This time whenever <code>CallSavedSub1</code> gets called it will execute the Perl subroutine <code>joe</code> (assuming it exists) rather than <code>fred</code> as was originally requested in the call to <code>SaveSub1</code>.</p>

<p>To get around these problems it is necessary to take a full copy of the SV. The code below shows <code>SaveSub2</code> modified to do that.</p>

<pre><code>    /* this isn&#39;t thread-safe */
    static SV * keepSub = (SV*)NULL;

    void
    SaveSub2(name)
        SV *	name
    	CODE:
     	/* Take a copy of the callback */
    	if (keepSub == (SV*)NULL)
    	    /* First time, so create a new SV */
	    keepSub = newSVsv(name);
    	else
    	    /* Been here before, so overwrite */
	    SvSetSV(keepSub, name);

    void
    CallSavedSub2()
    	CODE:
	PUSHMARK(SP);
	call_sv(keepSub, G_DISCARD|G_NOARGS);</code></pre>

<p>To avoid creating a new SV every time <code>SaveSub2</code> is called, the function first checks to see if it has been called before. If not, then space for a new SV is allocated and the reference to the Perl subroutine <code>name</code> is copied to the variable <code>keepSub</code> in one operation using <code>newSVsv</code>. Thereafter, whenever <code>SaveSub2</code> is called, the existing SV, <code>keepSub</code>, is overwritten with the new value using <code>SvSetSV</code>.</p>

<p>Note: using a static or global variable to store the SV isn&#39;t thread-safe. You can either use the <code>MY_CXT</code> mechanism documented in <a href="perlxs.html#Safely-Storing-Static-Data-in-XS">&quot;Safely Storing Static Data in XS&quot; in perlxs</a> which is fast, or store the values in perl global variables, using get_sv(), which is much slower.</p>

<h2 id="Using-call_argv"><a class="permalink" href="perlcall.html#Using-call_argv">#</a><a id="Using3"></a>Using call_argv</h2>

<p>Here is a Perl subroutine which prints whatever parameters are passed to it.</p>

<pre><code>sub PrintList
{
    my(@list) = @_;

    foreach (@list) { print &quot;$_\n&quot; }
}</code></pre>

<p>And here is an example of <i>call_argv</i> which will call <i>PrintList</i>.</p>

<pre><code>static char * words[] = {&quot;alpha&quot;, &quot;beta&quot;, &quot;gamma&quot;, &quot;delta&quot;, NULL};

static void
call_PrintList()
{
    call_argv(&quot;PrintList&quot;, G_DISCARD, words);
}</code></pre>

<p>Note that it is not necessary to call <code>PUSHMARK</code> in this instance. This is because <i>call_argv</i> will do it for you.</p>

<h2 id="Using-call_method"><a class="permalink" href="perlcall.html#Using-call_method">#</a><a id="Using4"></a>Using call_method</h2>

<p>Consider the following Perl code:</p>

<pre><code>{
    package Mine;

    sub new
    {
        my($type) = shift;
        bless [@_]
    }

    sub Display
    {
        my ($self, $index) = @_;
        print &quot;$index: $$self[$index]\n&quot;;
    }

    sub PrintID
    {
        my($class) = @_;
        print &quot;This is Class $class version 1.0\n&quot;;
    }
}</code></pre>

<p>It implements just a very simple class to manage an array. Apart from the constructor, <code>new</code>, it declares methods, one static and one virtual. The static method, <code>PrintID</code>, prints out simply the class name and a version number. The virtual method, <code>Display</code>, prints out a single element of the array. Here is an all-Perl example of using it.</p>

<pre><code>$a = Mine-&gt;new(&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;);
$a-&gt;Display(1);
Mine-&gt;PrintID;</code></pre>

<p>will print</p>

<pre><code class="plaintext">1: green
This is Class Mine version 1.0</code></pre>

<p>Calling a Perl method from C is fairly straightforward. The following things are required:</p>

<ul>

<li><p>A reference to the object for a virtual method or the name of the class for a static method</p>

</li>
<li><p>The name of the method</p>

</li>
<li><p>Any other parameters specific to the method</p>

</li>
</ul>

<p>Here is a simple XSUB which illustrates the mechanics of calling both the <code>PrintID</code> and <code>Display</code> methods from C.</p>

<pre><code>void
call_Method(ref, method, index)
    SV *	ref
    char *	method
    int		index
    CODE:
    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(ref);
    PUSHs(sv_2mortal(newSViv(index)));
    PUTBACK;

    call_method(method, G_DISCARD);

void
call_PrintID(class, method)
    char *	class
    char *	method
    CODE:
    PUSHMARK(SP);
    XPUSHs(sv_2mortal(newSVpv(class, 0)));
    PUTBACK;

    call_method(method, G_DISCARD);</code></pre>

<p>So the methods <code>PrintID</code> and <code>Display</code> can be invoked like this:</p>

<pre><code>$a = Mine-&gt;new(&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;);
call_Method($a, &#39;Display&#39;, 1);
call_PrintID(&#39;Mine&#39;, &#39;PrintID&#39;);</code></pre>

<p>The only thing to note is that, in both the static and virtual methods, the method name is not passed via the stack--it is used as the first parameter to <i>call_method</i>.</p>

<h2 id="Using-GIMME_V"><a class="permalink" href="perlcall.html#Using-GIMME_V">#</a><a id="Using5"></a>Using GIMME_V</h2>

<p>Here is a trivial XSUB which prints the context in which it is currently executing.</p>

<pre><code>void
PrintContext()
    CODE:
    U8 gimme = GIMME_V;
    if (gimme == G_VOID)
        printf (&quot;Context is Void\n&quot;);
    else if (gimme == G_SCALAR)
        printf (&quot;Context is Scalar\n&quot;);
    else
        printf (&quot;Context is Array\n&quot;);</code></pre>

<p>And here is some Perl to test it.</p>

<pre><code>PrintContext;
$a = PrintContext;
@a = PrintContext;</code></pre>

<p>The output from that will be</p>

<pre><code class="plaintext">Context is Void
Context is Scalar
Context is Array</code></pre>

<h2 id="Using-Perl-to-Dispose-of-Temporaries"><a class="permalink" href="perlcall.html#Using-Perl-to-Dispose-of-Temporaries">#</a><a id="Using6"></a>Using Perl to Dispose of Temporaries</h2>

<p>In the examples given to date, any temporaries created in the callback (i.e., parameters passed on the stack to the <i>call_*</i> function or values returned via the stack) have been freed by one of these methods:</p>

<ul>

<li><p>Specifying the G_DISCARD flag with <i>call_*</i></p>

</li>
<li><p>Explicitly using the <code>ENTER</code>/<code>SAVETMPS</code>--<code>FREETMPS</code>/<code>LEAVE</code> pairing</p>

</li>
</ul>

<p>There is another method which can be used, namely letting Perl do it for you automatically whenever it regains control after the callback has terminated. This is done by simply not using the</p>

<pre><code>ENTER;
SAVETMPS;
...
FREETMPS;
LEAVE;</code></pre>

<p>sequence in the callback (and not, of course, specifying the G_DISCARD flag).</p>

<p>If you are going to use this method you have to be aware of a possible memory leak which can arise under very specific circumstances. To explain these circumstances you need to know a bit about the flow of control between Perl and the callback routine.</p>

<p>The examples given at the start of the document (an error handler and an event driven program) are typical of the two main sorts of flow control that you are likely to encounter with callbacks. There is a very important distinction between them, so pay attention.</p>

<p>In the first example, an error handler, the flow of control could be as follows. You have created an interface to an external library. Control can reach the external library like this</p>

<pre><code class="plaintext">perl --&gt; XSUB --&gt; external library</code></pre>

<p>Whilst control is in the library, an error condition occurs. You have previously set up a Perl callback to handle this situation, so it will get executed. Once the callback has finished, control will drop back to Perl again. Here is what the flow of control will be like in that situation</p>

<pre><code class="plaintext">perl --&gt; XSUB --&gt; external library
                  ...
                  error occurs
                  ...
                  external library --&gt; call_* --&gt; perl
                                                      |
perl &lt;-- XSUB &lt;-- external library &lt;-- call_* &lt;----+</code></pre>

<p>After processing of the error using <i>call_*</i> is completed, control reverts back to Perl more or less immediately.</p>

<p>In the diagram, the further right you go the more deeply nested the scope is. It is only when control is back with perl on the extreme left of the diagram that you will have dropped back to the enclosing scope and any temporaries you have left hanging around will be freed.</p>

<p>In the second example, an event driven program, the flow of control will be more like this</p>

<pre><code class="plaintext">perl --&gt; XSUB --&gt; event handler
                  ...
                  event handler --&gt; call_* --&gt; perl
                                                   |
                  event handler &lt;-- call_* &lt;----+
                  ...
                  event handler --&gt; call_* --&gt; perl
                                                   |
                  event handler &lt;-- call_* &lt;----+
                  ...
                  event handler --&gt; call_* --&gt; perl
                                                   |
                  event handler &lt;-- call_* &lt;----+</code></pre>

<p>In this case the flow of control can consist of only the repeated sequence</p>

<pre><code class="plaintext">event handler --&gt; call_* --&gt; perl</code></pre>

<p>for practically the complete duration of the program. This means that control may <i>never</i> drop back to the surrounding scope in Perl at the extreme left.</p>

<p>So what is the big problem? Well, if you are expecting Perl to tidy up those temporaries for you, you might be in for a long wait. For Perl to dispose of your temporaries, control must drop back to the enclosing scope at some stage. In the event driven scenario that may never happen. This means that, as time goes on, your program will create more and more temporaries, none of which will ever be freed. As each of these temporaries consumes some memory your program will eventually consume all the available memory in your system--kapow!</p>

<p>So here is the bottom line--if you are sure that control will revert back to the enclosing Perl scope fairly quickly after the end of your callback, then it isn&#39;t absolutely necessary to dispose explicitly of any temporaries you may have created. Mind you, if you are at all uncertain about what to do, it doesn&#39;t do any harm to tidy up anyway.</p>

<h2 id="Strategies-for-Storing-Callback-Context-Information"><a class="permalink" href="perlcall.html#Strategies-for-Storing-Callback-Context-Information">#</a><a id="Strategies"></a>Strategies for Storing Callback Context Information</h2>

<p>Potentially one of the trickiest problems to overcome when designing a callback interface can be figuring out how to store the mapping between the C callback function and the Perl equivalent.</p>

<p>To help understand why this can be a real problem first consider how a callback is set up in an all C environment. Typically a C API will provide a function to register a callback. This will expect a pointer to a function as one of its parameters. Below is a call to a hypothetical function <code>register_fatal</code> which registers the C function to get called when a fatal error occurs.</p>

<pre><code>register_fatal(cb1);</code></pre>

<p>The single parameter <code>cb1</code> is a pointer to a function, so you must have defined <code>cb1</code> in your code, say something like this</p>

<pre><code>static void
cb1()
{
    printf (&quot;Fatal Error\n&quot;);
    exit(1);
}</code></pre>

<p>Now change that to call a Perl subroutine instead</p>

<pre><code>static SV * callback = (SV*)NULL;

static void
cb1()
{
    dSP;

    PUSHMARK(SP);

    /* Call the Perl sub to process the callback */
    call_sv(callback, G_DISCARD);
}


void
register_fatal(fn)
    SV *	fn
    CODE:
    /* Remember the Perl sub */
    if (callback == (SV*)NULL)
        callback = newSVsv(fn);
    else
        SvSetSV(callback, fn);

    /* register the callback with the external library */
    register_fatal(cb1);</code></pre>

<p>where the Perl equivalent of <code>register_fatal</code> and the callback it registers, <code>pcb1</code>, might look like this</p>

<pre><code># Register the sub pcb1
register_fatal(\&amp;pcb1);

sub pcb1
{
    die &quot;I&#39;m dying...\n&quot;;
}</code></pre>

<p>The mapping between the C callback and the Perl equivalent is stored in the global variable <code>callback</code>.</p>

<p>This will be adequate if you ever need to have only one callback registered at any time. An example could be an error handler like the code sketched out above. Remember though, repeated calls to <code>register_fatal</code> will replace the previously registered callback function with the new one.</p>

<p>Say for example you want to interface to a library which allows asynchronous file i/o. In this case you may be able to register a callback whenever a read operation has completed. To be of any use we want to be able to call separate Perl subroutines for each file that is opened. As it stands, the error handler example above would not be adequate as it allows only a single callback to be defined at any time. What we require is a means of storing the mapping between the opened file and the Perl subroutine we want to be called for that file.</p>

<p>Say the i/o library has a function <code>asynch_read</code> which associates a C function <code>ProcessRead</code> with a file handle <code>fh</code>--this assumes that it has also provided some routine to open the file and so obtain the file handle.</p>

<pre><code class="plaintext">asynch_read(fh, ProcessRead)</code></pre>

<p>This may expect the C <i>ProcessRead</i> function of this form</p>

<pre><code>void
ProcessRead(fh, buffer)
int	fh;
char *	buffer;
{
     ...
}</code></pre>

<p>To provide a Perl interface to this library we need to be able to map between the <code>fh</code> parameter and the Perl subroutine we want called. A hash is a convenient mechanism for storing this mapping. The code below shows a possible implementation</p>

<pre><code>static HV * Mapping = (HV*)NULL;

void
asynch_read(fh, callback)
    int	fh
    SV *	callback
    CODE:
    /* If the hash doesn&#39;t already exist, create it */
    if (Mapping == (HV*)NULL)
        Mapping = newHV();

    /* Save the fh -&gt; callback mapping */
    hv_store(Mapping, (char*)&amp;fh, sizeof(fh), newSVsv(callback), 0);

    /* Register with the C Library */
    asynch_read(fh, asynch_read_if);</code></pre>

<p>and <code>asynch_read_if</code> could look like this</p>

<pre><code>static void
asynch_read_if(fh, buffer)
int	fh;
char *	buffer;
{
    dSP;
    SV ** sv;

    /* Get the callback associated with fh */
    sv =  hv_fetch(Mapping, (char*)&amp;fh , sizeof(fh), FALSE);
    if (sv == (SV**)NULL)
        croak(&quot;Internal error...\n&quot;);

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(fh)));
    PUSHs(sv_2mortal(newSVpv(buffer, 0)));
    PUTBACK;

    /* Call the Perl sub */
    call_sv(*sv, G_DISCARD);
}</code></pre>

<p>For completeness, here is <code>asynch_close</code>. This shows how to remove the entry from the hash <code>Mapping</code>.</p>

<pre><code>void
asynch_close(fh)
    int	fh
    CODE:
    /* Remove the entry from the hash */
    (void) hv_delete(Mapping, (char*)&amp;fh, sizeof(fh), G_DISCARD);

    /* Now call the real asynch_close */
    asynch_close(fh);</code></pre>

<p>So the Perl interface would look like this</p>

<pre><code>sub callback1
{
    my($handle, $buffer) = @_;
}

# Register the Perl callback
asynch_read($fh, \&amp;callback1);

asynch_close($fh);</code></pre>

<p>The mapping between the C callback and Perl is stored in the global hash <code>Mapping</code> this time. Using a hash has the distinct advantage that it allows an unlimited number of callbacks to be registered.</p>

<p>What if the interface provided by the C callback doesn&#39;t contain a parameter which allows the file handle to Perl subroutine mapping? Say in the asynchronous i/o package, the callback function gets passed only the <code>buffer</code> parameter like this</p>

<pre><code>void
ProcessRead(buffer)
char *	buffer;
{
    ...
}</code></pre>

<p>Without the file handle there is no straightforward way to map from the C callback to the Perl subroutine.</p>

<p>In this case a possible way around this problem is to predefine a series of C functions to act as the interface to Perl, thus</p>

<pre><code>#define MAX_CB		3
#define NULL_HANDLE	-1
typedef void (*FnMap)();

struct MapStruct {
    FnMap    Function;
    SV *     PerlSub;
    int      Handle;
  };

static void  fn1();
static void  fn2();
static void  fn3();

static struct MapStruct Map [MAX_CB] =
    {
        { fn1, NULL, NULL_HANDLE },
        { fn2, NULL, NULL_HANDLE },
        { fn3, NULL, NULL_HANDLE }
    };

static void
Pcb(index, buffer)
int index;
char * buffer;
{
    dSP;

    PUSHMARK(SP);
    XPUSHs(sv_2mortal(newSVpv(buffer, 0)));
    PUTBACK;

    /* Call the Perl sub */
    call_sv(Map[index].PerlSub, G_DISCARD);
}

static void
fn1(buffer)
char * buffer;
{
    Pcb(0, buffer);
}

static void
fn2(buffer)
char * buffer;
{
    Pcb(1, buffer);
}

static void
fn3(buffer)
char * buffer;
{
    Pcb(2, buffer);
}

void
array_asynch_read(fh, callback)
    int		fh
    SV *	callback
    CODE:
    int index;
    int null_index = MAX_CB;

    /* Find the same handle or an empty entry */
    for (index = 0; index &lt; MAX_CB; ++index)
    {
        if (Map[index].Handle == fh)
            break;

        if (Map[index].Handle == NULL_HANDLE)
            null_index = index;
    }

    if (index == MAX_CB &amp;&amp; null_index == MAX_CB)
        croak (&quot;Too many callback functions registered\n&quot;);

    if (index == MAX_CB)
        index = null_index;

    /* Save the file handle */
    Map[index].Handle = fh;

    /* Remember the Perl sub */
    if (Map[index].PerlSub == (SV*)NULL)
        Map[index].PerlSub = newSVsv(callback);
    else
        SvSetSV(Map[index].PerlSub, callback);

    asynch_read(fh, Map[index].Function);

void
array_asynch_close(fh)
    int	fh
    CODE:
    int index;

    /* Find the file handle */
    for (index = 0; index &lt; MAX_CB; ++ index)
        if (Map[index].Handle == fh)
            break;

    if (index == MAX_CB)
        croak (&quot;could not close fh %d\n&quot;, fh);

    Map[index].Handle = NULL_HANDLE;
    SvREFCNT_dec(Map[index].PerlSub);
    Map[index].PerlSub = (SV*)NULL;

    asynch_close(fh);</code></pre>

<p>In this case the functions <code>fn1</code>, <code>fn2</code>, and <code>fn3</code> are used to remember the Perl subroutine to be called. Each of the functions holds a separate hard-wired index which is used in the function <code>Pcb</code> to access the <code>Map</code> array and actually call the Perl subroutine.</p>

<p>There are some obvious disadvantages with this technique.</p>

<p>Firstly, the code is considerably more complex than with the previous example.</p>

<p>Secondly, there is a hard-wired limit (in this case 3) to the number of callbacks that can exist simultaneously. The only way to increase the limit is by modifying the code to add more functions and then recompiling. None the less, as long as the number of functions is chosen with some care, it is still a workable solution and in some cases is the only one available.</p>

<p>To summarize, here are a number of possible methods for you to consider for storing the mapping between C and the Perl callback</p>

<dl>

<dt id="1.-Ignore-the-problem-Allow-only-1-callback"><a class="permalink" href="perlcall.html#1.-Ignore-the-problem-Allow-only-1-callback">#</a><a id="1"></a><a id="Ignore-the-problem---Allow-only-1-callback"></a>1. Ignore the problem - Allow only 1 callback</dt>
<dd>

<p>For a lot of situations, like interfacing to an error handler, this may be a perfectly adequate solution.</p>

</dd>
<dt id="2.-Create-a-sequence-of-callbacks-hard-wired-limit"><a class="permalink" href="perlcall.html#2.-Create-a-sequence-of-callbacks-hard-wired-limit">#</a><a id="2"></a><a id="Create-a-sequence-of-callbacks---hard-wired-limit"></a>2. Create a sequence of callbacks - hard wired limit</dt>
<dd>

<p>If it is impossible to tell from the parameters passed back from the C callback what the context is, then you may need to create a sequence of C callback interface functions, and store pointers to each in an array.</p>

</dd>
<dt id="3.-Use-a-parameter-to-map-to-the-Perl-callback"><a class="permalink" href="perlcall.html#3.-Use-a-parameter-to-map-to-the-Perl-callback">#</a><a id="3"></a><a id="Use-a-parameter-to-map-to-the-Perl-callback"></a>3. Use a parameter to map to the Perl callback</dt>
<dd>

<p>A hash is an ideal mechanism to store the mapping between C and Perl.</p>

</dd>
</dl>

<h2 id="Alternate-Stack-Manipulation"><a class="permalink" href="perlcall.html#Alternate-Stack-Manipulation">#</a><a id="Alternate"></a>Alternate Stack Manipulation</h2>

<p>Although I have made use of only the <code>POP*</code> macros to access values returned from Perl subroutines, it is also possible to bypass these macros and read the stack using the <code>ST</code> macro (See <a href="perlxs.html">perlxs</a> for a full description of the <code>ST</code> macro).</p>

<p>Most of the time the <code>POP*</code> macros should be adequate; the main problem with them is that they force you to process the returned values in sequence. This may not be the most suitable way to process the values in some cases. What we want is to be able to access the stack in a random order. The <code>ST</code> macro as used when coding an XSUB is ideal for this purpose.</p>

<p>The code below is the example given in the section <a href="perlcall.html#Returning-a-List-of-Values">&quot;Returning a List of Values&quot;</a> recoded to use <code>ST</code> instead of <code>POP*</code>.</p>

<pre><code>static void
call_AddSubtract2(a, b)
int a;
int b;
{
    dSP;
    I32 ax;
    int count;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(a)));
    PUSHs(sv_2mortal(newSViv(b)));
    PUTBACK;

    count = call_pv(&quot;AddSubtract&quot;, G_ARRAY);

    SPAGAIN;
    SP -= count;
    ax = (SP - PL_stack_base) + 1;

    if (count != 2)
        croak(&quot;Big trouble\n&quot;);

    printf (&quot;%d + %d = %d\n&quot;, a, b, SvIV(ST(0)));
    printf (&quot;%d - %d = %d\n&quot;, a, b, SvIV(ST(1)));

    PUTBACK;
    FREETMPS;
    LEAVE;
}</code></pre>

<p>Notes</p>

<ol>

<li><p>Notice that it was necessary to define the variable <code>ax</code>. This is because the <code>ST</code> macro expects it to exist. If we were in an XSUB it would not be necessary to define <code>ax</code> as it is already defined for us.</p>

</li>
<li><p>The code</p>

<pre><code>SPAGAIN;
SP -= count;
ax = (SP - PL_stack_base) + 1;</code></pre>

<p>sets the stack up so that we can use the <code>ST</code> macro.</p>

</li>
<li><p>Unlike the original coding of this example, the returned values are not accessed in reverse order. So <code>ST(0)</code> refers to the first value returned by the Perl subroutine and <code>ST(count-1)</code> refers to the last.</p>

</li>
</ol>

<h2 id="Creating-and-Calling-an-Anonymous-Subroutine-in-C"><a class="permalink" href="perlcall.html#Creating-and-Calling-an-Anonymous-Subroutine-in-C">#</a><a id="Creating"></a>Creating and Calling an Anonymous Subroutine in C</h2>

<p>As we&#39;ve already shown, <code>call_sv</code> can be used to invoke an anonymous subroutine. However, our example showed a Perl script invoking an XSUB to perform this operation. Let&#39;s see how it can be done inside our C code:</p>

<pre><code>...

SV *cvrv
   = eval_pv(&quot;sub {
               print &#39;You will not find me cluttering any namespace!&#39;
              }&quot;, TRUE);

...

call_sv(cvrv, G_VOID|G_NOARGS);</code></pre>

<p><code>eval_pv</code> is used to compile the anonymous subroutine, which will be the return value as well (read more about <code>eval_pv</code> in <a href="perlapi.html#eval_pv">&quot;eval_pv&quot; in perlapi</a>). Once this code reference is in hand, it can be mixed in with all the previous examples we&#39;ve shown.</p>

<h1 id="LIGHTWEIGHT-CALLBACKS"><a class="permalink" href="perlcall.html#LIGHTWEIGHT-CALLBACKS">#</a><a id="LIGHTWEIGHT"></a>LIGHTWEIGHT CALLBACKS</h1>

<p>Sometimes you need to invoke the same subroutine repeatedly. This usually happens with a function that acts on a list of values, such as Perl&#39;s built-in sort(). You can pass a comparison function to sort(), which will then be invoked for every pair of values that needs to be compared. The first() and reduce() functions from <a href="./List::Util.html">List::Util</a> follow a similar pattern.</p>

<p>In this case it is possible to speed up the routine (often quite substantially) by using the lightweight callback API. The idea is that the calling context only needs to be created and destroyed once, and the sub can be called arbitrarily many times in between.</p>

<p>It is usual to pass parameters using global variables (typically $_ for one parameter, or $a and $b for two parameters) rather than via @_. (It is possible to use the @_ mechanism if you know what you&#39;re doing, though there is as yet no supported API for it. It&#39;s also inherently slower.)</p>

<p>The pattern of macro calls is like this:</p>

<pre><code>    dMULTICALL;			/* Declare local variables */
    U8 gimme = G_SCALAR;	/* context of the call: G_SCALAR,
				 * G_ARRAY, or G_VOID */

    PUSH_MULTICALL(cv);		/* Set up the context for calling cv,
				   and set local vars appropriately */

    /* loop */ {
        /* set the value(s) af your parameter variables */
        MULTICALL;		/* Make the actual call */
    } /* end of loop */

    POP_MULTICALL;		/* Tear down the calling context */</code></pre>

<p>For some concrete examples, see the implementation of the first() and reduce() functions of List::Util 1.18. There you will also find a header file that emulates the multicall API on older versions of perl.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="perlcall.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p><a href="perlxs.html">perlxs</a>, <a href="perlguts.html">perlguts</a>, <a href="perlembed.html">perlembed</a></p>

<h1 id="AUTHOR"><a class="permalink" href="perlcall.html#AUTHOR">#</a>AUTHOR</h1>

<p>Paul Marquess</p>

<p>Special thanks to the following people who assisted in the creation of the document.</p>

<p>Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy and Larry Wall.</p>

<h1 id="DATE"><a class="permalink" href="perlcall.html#DATE">#</a>DATE</h1>

<p>Last updated for perl 5.23.1.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
